﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace CarlosMisfortune.model
{
    class AnimatedSprite
    {
        #region Fields
        private string[] m_nameList;
        private Texture2D m_sheet;
        private Dictionary<string, Rectangle> m_data;

        private bool m_LoopAnimation = true;
        private bool m_finishedPlaying = false;
        private float m_frameTimer = 0.0f;
        private float m_frameDelay = 0.05f;
        private int m_currentFrame;
        #endregion

        #region Properties
        public Texture2D Sheet 
        {
            get { return m_sheet; }
            set { m_sheet = value; }
        }

        public Dictionary<string, Rectangle> Data 
        {
            get { return m_data; }
            set { m_data = value; }
        }

        public int FrameCount
        {
            get { return Data.Count; }
        }

        public int CurrentFrame
        {
            get { return m_currentFrame; }
            set { m_currentFrame = value; }
        }

        public Point FrameSize
        {
            get
            {
                return new Point(
                    Data[m_nameList[m_currentFrame]].Width,
                    Data[m_nameList[m_currentFrame]].Height);
            }
        }

        public Rectangle CurrentRectangle
        {
            get 
            {                
                if (m_nameList == null) 
                {
                    m_nameList = Data.Keys.ToArray();
                }
                return Data[m_nameList[m_currentFrame]];
            }
        }
        #endregion

        #region Contstructor
        public AnimatedSprite()
        {
            Initialize();
        }
        #endregion

        #region Public Methods
        public void Initialize()
        {
            m_currentFrame = 0;
            m_finishedPlaying = false;
        }

        public void Update(GameTime a_gameTime)
        {
            float elapsedTime = (float)a_gameTime.ElapsedGameTime.TotalSeconds;

            m_frameTimer += elapsedTime;

            if (m_frameTimer >= m_frameDelay)
            {
                if (m_currentFrame < (FrameCount - 1))
                {
                    m_currentFrame++;
                }
                else
                {
                    if (m_LoopAnimation)
                    {
                        m_currentFrame = 0;
                    }
                    else
                    {
                        m_currentFrame = FrameCount - 1;
                        m_finishedPlaying = true;
                    }
                }
                m_frameTimer = 0.0f;
            }
        }
        #endregion
    }
}
